package top.jolyoulu.sql

import org.apache.spark.sql.{DataFrame, SaveMode, SparkSession}
import org.apache.spark.{SparkConf, SparkContext}

/**
 * @Author: JolyouLu
 * @Date: 2024/5/16 19:21
 * @Description
 */
object Spark01_SparkSQL_JDBC {
  def main(args: Array[String]): Unit = {
    //创建SparkSQL的运行环境
    val sparkSQL: SparkConf = new SparkConf().setMaster("local[*]").setAppName("SparkSQL")
    val spark = SparkSession.builder().config(sparkSQL).getOrCreate()
    val sc: SparkContext = spark.sparkContext
    import spark.implicits._
    //从Mysql加载数据
    val df: DataFrame = spark.read
      .format("jdbc")
      .option("url", "jdbc:mysql://192.168.88.100:3306/admin") //数据源地址
      .option("driver", "com.mysql.jdbc.Driver") //驱动
      .option("user", "root") //mysql 用户名
      .option("password", "123456") //mysql 密码
      .option("dbtable", "sys_user") //操作的表
      .load()

    df.show()

    //保存数据到一个新表中
    df.write
      .format("jdbc")
      .option("url", "jdbc:mysql://192.168.88.100:3306/admin")
      .option("driver", "com.mysql.jdbc.Driver")
      .option("user", "root")
      .option("password", "123456")
      .option("dbtable", "sys_user1")
      .mode(SaveMode.Append)
      .save()

    //关闭环境
    spark.close()
  }
}
